package org.example.controller;

import cn.hutool.core.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.example.controller.viewobject.UserVo;
import org.example.error.BusinessException;
import org.example.error.EmBusinessError;
import org.example.regex.RegexUtils;
import org.example.response.CommonReturnType;
import org.example.service.UserService;
import org.example.service.impl.UserServiceImpl;
import org.example.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

//controller做了到用户viewobject的传输，保证了UI只使用到他需要的展示字段即可
@Controller("User")
@RequestMapping(value = "user")
@CrossOrigin(originPatterns = "*", allowedHeaders = "*", allowCredentials = "true")
public class UserController extends BaseController {


    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private HttpServletRequest httpServletRequest;
    //用户登录接口
    @PostMapping(value = "login",consumes ={CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonReturnType login(@RequestParam(name = "telphone") String telphone,
                                  @RequestParam(name = "password") String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //判断手机号和密码
        if (StringUtils.isEmpty(telphone)||
            StringUtils.isEmpty(password)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        //用户登录合法，用来校验用户登录是否合法
       UserModel userModel= userService.login(telphone,EncodeByMd5(password));
       /* //将登录凭着加入到用户登录成功的redis
        this.redisTemplate.opsForValue().set("IS_LOGIN", String.valueOf(true));
        this.redisTemplate.opsForValue().set("LOGIN_USER", String.valueOf(userModel));*/
      httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
      httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel);
        return CommonReturnType.creat(null);
    }

    //用户注册接口
    @PostMapping(value = "register", consumes = {CONTENT_TYPE_FORMED})
    // @RequestMapping(value = "register",method = {RequestMethod.POST},consumes = "application/x-www-form-urlencoded")
    @ResponseBody
    public CommonReturnType register(@RequestParam(name = "telphone") String telphone,
                                     @RequestParam(name = "otpCode") String otpCode,
                                     @RequestParam(name = "name") String name,
                                     @RequestParam(name = "age") Integer age,
                                     @RequestParam(name = "password") String password,
                                     @RequestParam(name = "gender") Integer gender) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //验证手机号与验证码是否匹配
        String SessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(telphone);
        // String SessionOtpCode = this.httpServletRequest.getParameter("otpCode");
        if (!StringUtils.equals(otpCode, SessionOtpCode)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "验证码不符合");
        }
        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setGender(new Byte(String.valueOf(gender)));
        userModel.setAge(age);
        userModel.setTelphone(telphone);
        userModel.setRegisterMode("byphone");
        userModel.setEncrptPassword(EncodeByMd5(password));
        userService.register(userModel);
        return CommonReturnType.creat(null);

    }

    //确定计算方法     00000000
    public String EncodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();

        String newstr = base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }

    @PostMapping(value = "getotp", consumes = {CONTENT_TYPE_FORMED})
    @ResponseBody
    //用户获取otp短信
    public CommonReturnType getOtp(@RequestParam(name = "telphone") String telphone) {

        if (RegexUtils.isPhoneInvalid(telphone)) {
            //返回错误信息
            return CommonReturnType.creat("null", "不合法");
        }

        //需要按照一定的规则生成OTP验证码
       // String otpcode= RandomUtil.randomNumbers(Integer.parseInt("6"));
        Random random = new Random();
        int randomInt = random.nextInt(999999);
        randomInt += 10000;
        String otpCode = String.valueOf(randomInt);


        //将OTP验证码与对应用户的手机号关联
        //redisTemplate.opsForValue().set(telphone,otpCode);
        httpServletRequest.getSession().setAttribute(telphone, otpCode);
        //存进redis
       /* ValueOperations operations = redisTemplate.opsForValue();
        operations.set(telphone, otpCode);*/

        System.err.println(this.httpServletRequest.getSession().getId());

        //将OTP验证码通过短信验证发送给用户
        System.out.println("templhone:" + telphone + "otpCode:" + otpCode);
        System.err.println(this.httpServletRequest.getSession().getId());
        return CommonReturnType.creat(null);
    }

    @RequestMapping(value = "get")
    @ResponseBody
    public CommonReturnType getUser(@RequestParam(name = "id") Integer id) throws BusinessException {
        //调用service服务获取对应id的用户对象并返回非前端
        UserModel userModel = userService.getByUserid(id);
        // //将核心领域模型对象转化为可用给UI使用的viewobject
        UserVo userVO = convertFromModel(userModel);
        //如果用户不存在
        if (userModel == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        //返回通用对象

        return CommonReturnType.creat(userVO);
    }

    private UserVo convertFromModel(UserModel userModel) {
        if (userModel == null) {
            return null;
        }
        UserVo userVo = new UserVo();
        //BeanUtils.copyProperties（a的属性copy到b），
        BeanUtils.copyProperties(userModel, userVo);
        return userVo;
    }

}